/*
 *  (c) 2005-2009 Richard Cowin (http://openrico.org)
 *  (c) 2005-2009 Matt Brown (http://dowdybrown.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 *  file except in compliance with the License. You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software distributed under the
 *  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 *  either express or implied. See the License for the specific language governing permissions
 *  and limitations under the License.
 */

Rico.KeywordSearch = function(id,options) {
  this.initialize(id,options);
};

Rico.KeywordSearch.prototype = {
/**
 * @class Implements a pop-up keyword search control.
 * @extends Rico.Popup
 * @constructs
 * @param id unique identifier
 * @param options object may contain any of the following:<dl>
 *   <dt>showColorCode</dt><dd> show hex color code as user hovers over color grid? default=false</dd>
 *   <dt>cellsPerRow  </dt><dd> number of colors per row in the grid? default=18</dd>
 *   <dt>palette      </dt><dd> array of 6 digit hex values, default=216 "web safe" colors</dd>
 *</dl>
 */
  initialize: function(id,options) {
    this.id=id;
    Rico.extend(this, new Rico.Window(Rico.getPhraseById("keywordTitle"),options));
    this.contentCell.className='ricoKeywordSearch';
    Rico.extend(this.options, {
      listLength : 10,
      maxSuggest : 20,
      width: '12em'
    });
  },

  atLoad : function() {
    this.searchField=Rico.createFormField(this.contentDiv,'input','text',this.id+'_search');
    this.searchField.style.display="block";
    this.searchField.style.width=this.options.width;
    Rico.eventBind(this.searchField,'keyup',Rico.eventHandle(this,'filterKeypress'),false);
    this.selectList=Rico.createFormField(this.contentDiv,'select',null,this.id+'_list');
    this.selectList.size=this.options.listLength;
    this.selectList.style.display="block";
    this.selectList.style.width=this.options.width;
    Rico.eventBind(this.selectList,'change',Rico.eventHandle(this,'listClick'),false);
    /**
     * alias for closePopup
     * @function
     */
    this.close=this.closePopup;
    this.close();
  },
  
  open: function(currentVal,column) {
    this.column=column;
    this.grid=this.column.liveGrid;
    this.searchField.value='';
    this.selectList.options.length=0;
    this.openPopup();
    this.searchField.focus();
    this.selectValuesRequest('');
  },

  selectValuesRequest: function(filter) {
    var colnum=this.column.index;
    var options={};
    Rico.extend(options, this.grid.buffer.ajaxOptions);
    options.parameters = {id: this.grid.tableId, offset: '0', page_size: this.options.maxSuggest, edit: colnum};
    options.parameters[this.grid.actionId]="query";
    if (filter!='' && filter!='*') {
      if (filter.indexOf('*')==-1) filter='*'+filter+'*';
      options.parameters['f[1][op]']="LIKE";
      options.parameters['f[1][len]']=1;
      options.parameters['f[1][0]']=filter;
    }
    options.onComplete = Rico.bind(this,'selectValuesUpdate');
    new Rico.ajaxRequest(this.grid.buffer.dataSource, options);
  },

  selectValuesUpdate: function(request) {
    var response = request.responseXML.getElementsByTagName("ajax-response");
    Rico.log("selectValuesUpdate: "+request.status);
    if (response == null || response.length != 1) return;
    response=response[0];
    var error = response.getElementsByTagName('error');
    if (error.length > 0) {
      var errmsg=Rico.getContentAsString(error[0],this.grid.buffer.isEncoded);
      Rico.log("Data provider returned an error:\n"+errmsg);
      alert(Rico.getPhraseById("requestError",errmsg));
      return null;
    }
    this.selectList.options.length=0;
    response=response.getElementsByTagName('response')[0];
    var rowsElement = response.getElementsByTagName('rows')[0];
    var rows = this.grid.buffer.dom2jstable(rowsElement);
    Rico.log("selectValuesUpdate: id="+this.selectList.id+' rows='+rows.length);
    for (var i=0; i<rows.length; i++) {
      if (rows[i].length>0) {
        var c0=rows[i][0];
        var c1=(rows[i].length>1) ? rows[i][1] : c0;
        Rico.addSelectOption(this.selectList,c0,c1);
      }
    }
  },

  filterKeypress: function(e) {
    var txtbox=Rico.eventElement(e);
    if (typeof this.lastKeyFilter != 'string') this.lastKeyFilter='';
    if (this.lastKeyFilter==txtbox.value) return;
    var v=txtbox.value;
    Rico.log("filterKeypress: "+this.index+' '+v);
    this.lastKeyFilter=v;
    this.selectValuesRequest(v);
  },
  
  listClick: function(e) {
    var elem=Rico.eventElement(e);
    if (elem.tagName.toLowerCase() != 'select') return;
    if (this.returnValue) {
      var opt=elem.options[elem.selectedIndex];
      this.returnValue(opt.value,opt.innerHTML);
    }
    this.close();
  }

};

Rico.includeLoaded('ricoSearch.js');
